<!DOCTYPE html>
<html lang="zh-CN">
  <head>
  <meta charset="UTF-8">
  <meta 
    name="viewport"
    content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
  <meta 
    http-equiv="X-UA-Compatible" 
    content="ie=edge">
  <meta 
    name="theme-color" 
    content="#fff" 
    id="theme-color">
  <meta 
    name="description" 
    content="Gas">
  <link 
    rel="icon" 
    href="/img/Kaze.png">
  <title>SpringBoot-Redis-过期事件</title>
  
    
      <meta 
        property="og:title" 
        content="SpringBoot-Redis-过期事件">
    
    
      <meta 
        property="og:url" 
        content="http://example.com/2021/08/06/SpringBoot-Redis-%E8%BF%87%E6%9C%9F%E4%BA%8B%E4%BB%B6/index.html">
    
    
      <meta 
        property="og:img" 
        content="/img/Kaze.png">
    
    
    
      <meta 
        property="og:type" 
        content="article">
      <meta 
        property="og:article:published_time" 
        content="2021-08-06">
      <meta 
        property="og:article:modified_time" 
        content="2021-08-09">
      <meta 
        property="og:article:author" 
        content="Gas">
      
        
          <meta 
            property="og:article:tag" 
            content="SpringBoot">
        
          <meta 
            property="og:article:tag" 
            content="Redis">
        
      
    
  
  <script>
    function loadScript(url, cb) {
      var script = document.createElement('script');
      script.src = url;
      if (cb) script.onload = cb;
      script.async = true;
      document.body.appendChild(script);
    }
    function loadCSS(href, data, attr) {
      var sheet = document.createElement('link');
      sheet.ref = 'stylesheet';
      sheet.href = href;
      sheet.dataset[data] = attr;
      document.head.appendChild(sheet);
    }
    function changeCSS(cssFile, data, attr) {
      var oldlink = document.querySelector(data);
      var newlink = document.createElement("link");
      newlink.setAttribute("rel", "stylesheet");
      newlink.setAttribute("href", cssFile);
      newlink.dataset.prism = attr;
      document.head.replaceChild(newlink, oldlink);
    }
  </script>
  
    
      
      
      
      
        
        
        
        <script>
          function prismThemeChange() {
            if(document.getElementById('theme-color').dataset.mode === 'dark') {
              if(document.querySelector('[data-prism]')) {
                changeCSS('/js/lib/prism/prism-tomorrow.min.css', '[data-prism]', 'prism-tomorrow');
              } else {
                loadCSS('/js/lib/prism/prism-tomorrow.min.css', 'prism', 'prism-tomorrow');
              }
            } else {
              if(document.querySelector('[data-prism]')) {
                changeCSS('/js/lib/prism/prism-okaidia.min.css', '[data-prism]', 'prism-okaidia');
              } else {
                loadCSS('/js/lib/prism/prism-okaidia.min.css', 'prism', 'prism-okaidia');
              }
            }
          }
          prismThemeChange()
        </script>
      
      
        
        <link rel="stylesheet" href="/js/lib/prism/prism-line-numbers.min.css">
      
    
  
  <script>
    // control reverse button
    var reverseDarkList = {
      dark: 'light',
      light: 'dark'
    };
    var themeColor = {
      dark: '#1c1c1e',
      light: '#fff'
    }
    // get the data of css prefers-color-scheme
    var getCssMediaQuery = function() {
      return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    };
    // reverse current darkmode setting function
    var reverseDarkModeSetting = function() {
      var setting = localStorage.getItem('user-color-scheme');
      if(reverseDarkList[setting]) {
        setting = reverseDarkList[setting];
      } else if(setting === null) {
        setting = reverseDarkList[getCssMediaQuery()];
      } else {
        return;
      }
      localStorage.setItem('user-color-scheme', setting);
      return setting;
    };
    // apply current darkmode setting
  </script>
  
    <script>
      var setDarkmode = function(mode) {
      var setting = mode || localStorage.getItem('user-color-scheme');
      if(setting === getCssMediaQuery()) {
        document.documentElement.removeAttribute('data-user-color-scheme');
        localStorage.removeItem('user-color-scheme');
        document.getElementById('theme-color').content = themeColor[setting];
        document.getElementById('theme-color').dataset.mode = setting;
        prismThemeChange();
      } else if(reverseDarkList[setting]) {
        document.documentElement.setAttribute('data-user-color-scheme', setting);
        document.getElementById('theme-color').content = themeColor[setting];
        document.getElementById('theme-color').dataset.mode = setting;
        prismThemeChange();
      } else {
        document.documentElement.removeAttribute('data-user-color-scheme');
        localStorage.removeItem('user-color-scheme');
        document.getElementById('theme-color').content = themeColor[getCssMediaQuery()];
        document.getElementById('theme-color').dataset.mode = getCssMediaQuery();
        prismThemeChange();
      }
    };
    setDarkmode();
    </script>
  
  
  <link rel="preload" href="//at.alicdn.com/t/font_1946621_i1kgafibvw.css" as="style" >
  <link rel="preload" href="//at.alicdn.com/t/font_1952792_89b4ac4k4up.css" as="style" >
  
  
    <link rel="preload" href="/js/lib/lightbox/baguetteBox.min.js" as="script">
    <link rel="preload" href="/js/lib/lightbox/baguetteBox.min.css" as="style" >
  
  
    <link rel="preload" href="/js/lib/lozad.min.js" as="script">
  
  
  
  
  
  
  
  <link rel="stylesheet" href="/css/main.css">
  
  <link rel="stylesheet" href="//at.alicdn.com/t/font_1946621_i1kgafibvw.css">
  
  <link rel="stylesheet" href="//at.alicdn.com/t/font_1952792_89b4ac4k4up.css">
  <link rel="stylesheet" href="//at.alicdn.com/t/font_2818401_duebq0kmk47.css">
  
    <link rel="stylesheet" href="/js/lib/lightbox/baguetteBox.min.css">
  
<meta name="generator" content="Hexo 5.4.0"></head>

  <body>
    <div class="wrapper">
       
      <nav class="navbar">
  <div class="navbar-logo">
    <span class="navbar-logo-main">
      
        <img 
          class="navbar-logo-img" 
          src="/img/Kaze.png" 
          alt="blog logo">
      
      <span class="navbar-logo-dsc">Gas</span>
    </span>
  </div>
  <div class="navbar-menu">
    
      <a 
        href="/" 
        class="navbar-menu-item">
        
          首页
        
      </a>
    
      <a 
        href="/archives" 
        class="navbar-menu-item">
        
          归档
        
      </a>
    
      <a 
        href="/tags" 
        class="navbar-menu-item">
        
          标签
        
      </a>
    
      <a 
        href="/categories" 
        class="navbar-menu-item">
        
          分类
        
      </a>
    
      <a 
        href="/about" 
        class="navbar-menu-item">
        
          关于
        
      </a>
    
      <a 
        href="/links" 
        class="navbar-menu-item">
        
          友链
        
      </a>
    
    <a 
      class="navbar-menu-item darknavbar" 
      id="dark">
      <i class="iconfont icon-weather"></i>
    </a>
    <a 
      class="navbar-menu-item searchnavbar" 
      id="search">
      <i 
        class="iconfont icon-search" 
        style="font-size: 1.2rem; font-weight: 400;">
      </i>
    </a>
  </div>
</nav> 
      
      <div 
        id="local-search" 
        style="display: none">
        <input
          class="navbar-menu-item"
          id="search-input"
          placeholder="请输入搜索内容..." />
        <div id="search-content"></div>
      </div>
      
      <div class="section-wrap">
        <div class="container">
          <div class="columns">
            <main class="main-column">
<article class="card card-content">
  <header>
    <h1 class="post-title">
      SpringBoot-Redis-过期事件
    </h1>
  </header>
  <div class="post-meta post-show-meta">
    <time datetime="2021-08-06T09:39:11.000Z">
      <i 
        class="iconfont icon-calendar" 
        style="margin-right: 2px;">
      </i>
      <span>2021-08-06</span>
    </time>
    
      <span class="dot"></span>
      
        <a 
          href="/categories/SpringBoot/" 
          class="post-meta-link">
          SpringBoot
        </a>
      
    
    
      <span class="dot"></span>
      <span>1.6k 字</span>
    
  </div>
  
    <div 
      class="post-meta post-show-meta" 
      style="margin-top: -10px;">
      <div style="display: flex; align-items: center;">
        <i 
          class="iconfont icon-biaoqian" 
          style="margin-right: 2px; font-size: 1.15rem;">
        </i>
        
          
          <a 
            href="/tags/SpringBoot/" 
            class="post-meta-link">
            SpringBoot
          </a>
        
          
            <span class="dot"></span>
          
          <a 
            href="/tags/Redis/" 
            class="post-meta-link">
            Redis
          </a>
        
      </div>
    </div>
  
  </header>
  <div 
    id="section" 
    class="post-content">
    <h2 id="需求"><a href="#需求" class="headerlink" title="需求"></a>需求</h2><p>需要实现一个超时通知的功能,又不想定时任务扫,所以就百度百度发现了这个,Redis的过期监听事件,就是向Redis里存放一条记录,把需要的信息存在key中,设置过期事件,一旦过期,就触发事件.</p>
<h2 id="实现"><a href="#实现" class="headerlink" title="实现"></a>实现</h2><p>要实现这个功能,需要先修改Redis的配置文件.</p>
<p>打开<code>.conf</code>文件,找到<code>notify-keyspace-events</code>这个值,默认值为” “,将其修改为<code>notify-keyspace-events Ex</code></p>
<p>也可以通过命令设置,执行如下</p>
<pre class="line-numbers language-none"><code class="language-none">&#x2F;&#x2F;修改
config set notify-keyspace-events &quot;Ex&quot;
&#x2F;&#x2F;查看
config get notify-keyspace-events<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<h3 id="参数解析"><a href="#参数解析" class="headerlink" title="参数解析"></a>参数解析</h3><table>
<thead>
<tr>
<th>字符</th>
<th>发送通知</th>
</tr>
</thead>
<tbody><tr>
<td>K</td>
<td>键空间通知，所有通知以 <strong>keyspace@</strong> 为前缀，针对Key</td>
</tr>
<tr>
<td>E</td>
<td>键事件通知，所有通知以 <strong>keyevent@</strong> 为前缀，针对event</td>
</tr>
<tr>
<td><em>g</em></td>
<td><em>DEL 、 EXPIRE 、 RENAME 等类型无关的通用命令的通知</em></td>
</tr>
<tr>
<td><strong>$</strong></td>
<td><strong>字符串命令的通知</strong></td>
</tr>
<tr>
<td><strong>l</strong></td>
<td><strong>列表命令的通知</strong></td>
</tr>
<tr>
<td><strong>s</strong></td>
<td><strong>集合命令的通知</strong></td>
</tr>
<tr>
<td><strong>h</strong></td>
<td><strong>哈希命令的通知</strong></td>
</tr>
<tr>
<td><strong>z</strong></td>
<td><strong>有序集合命令的通知</strong></td>
</tr>
<tr>
<td><em>x</em></td>
<td><em>过期事件：每当有过期键被删除时发送</em></td>
</tr>
<tr>
<td><em>e</em></td>
<td><em>驱逐(evict)事件：每当有键因为 maxmemory 政策而被删除时发送</em></td>
</tr>
<tr>
<td>A</td>
<td>参数 g$lshzxe 的别名，相当于是All</td>
</tr>
</tbody></table>
<p>输入的参数中至少需要一个 <code>K</code> 或者 <code>E</code>,不然不会触发任何通知</p>
<p>斜体 表示通用的操作或者事件</p>
<p>粗体 表示特定数据类型的操作</p>
<h2 id="事件类型"><a href="#事件类型" class="headerlink" title="事件类型"></a>事件类型</h2><p>对于每个修改数据库的操作,键空间通知都会发送两种不同类型的事件消息: <code>keyspace</code> 和  <code>keyevent</code>.</p>
<p>以<code>keyspace</code>为前缀的频道被称为 键空间通知<code>key-space notification</code></p>
<p>以<code>keyevent</code>为前缀的频道被称为 键事件通知<code>key-event notification</code></p>
<p>事件通知是以 <code>__keyspace@DB __: KeyPattern</code> 或 <code>__keyevent@DB__:OpsType</code> 的格式来发送信息的.</p>
<p><code>DB</code>表示第几个数据库</p>
<p><code>KeyPattern</code>表示需要监控的键模式,可以用通配符.</p>
<p><code>OpsType</code>表示操作类型</p>
<p>所以,如果想订阅特殊的<code>Key</code>上的事件,应该订阅<code>Keyspace</code></p>
<p>所以执行对<code>0</code>号数据库的<code>myKey</code>键执行<code>DEL</code>操作时,系统将发布两条消息, 相当于执行以下两个 <a target="_blank" rel="noopener" href="https://redis.io/topics/pubsub">publish</a> 命令：</p>
<pre class="line-numbers language-none"><code class="language-none">PUBLISH __keyspace@0__:myKey del
PUBLISH __keyevent@0__:del  myKey<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p>订阅第一个频道 <code>__keyspace@0__:myKey</code> 可以接收0号数据库所有修改<code>myKey</code>的事件</p>
<p>订阅第二个频道 <code>__keyevent@0__:del</code> 可以接收0号数据库所有执行<code>del</code>命令的键</p>
<h2 id="订阅"><a href="#订阅" class="headerlink" title="订阅"></a>订阅</h2><p>使用<code>subscribe </code>和<code>psubscribe</code>命令来对特点主题进行订阅,完成通知的过程</p>
<pre class="line-numbers language-none"><code class="language-none">SUBSCRIBE channel [channel ...]
PSUBSCRIBE channelPattern [channelPattern ...]<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span></span></code></pre>

<p><code>PSUBSCRIBE</code>对比<code>SUBSCRIBE</code>唯一不同就是支持通配符,每个模式以 * 作为匹配符,比如 huangz* 匹配所有以 huangz.显然支持通配符的性能消耗会大一点.</p>
<h2 id="命令实践"><a href="#命令实践" class="headerlink" title="命令实践"></a>命令实践</h2><p> 1：订阅</p>
<pre><code>    <pre class="line-numbers language-none"><code class="language-none">subscribe __keyspace@0__:cool
Reading messages... (press Ctrl-C to quit)
1) &quot;subscribe&quot;                   # 返回值的类型：显示订阅成功
2) &quot;__keyspace@0__:cool&quot;         # 订阅的Channel名
3) (integer) 1                   # 目前已订阅的频道数量<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span></span></code></pre>
</code></pre>
<p>2：设置失效</p>
<pre><code>  <pre class="line-numbers language-none"><code class="language-none">setex cool 1 val                 # cool&#x3D;val 1秒失效<span aria-hidden="true" class="line-numbers-rows"><span></span></span></code></pre>
</code></pre>
<p>3：失效消息</p>
<pre class="line-numbers language-none"><code class="language-none">1)&quot;message&quot;                      # 返回值的类型：信息
2)__keyspace@0__:cool”           # 来源(从哪个Channel发送过来)
3) “expired&quot;                     # 信息内容<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span></span></code></pre>

<p>注：对于psubscribe，消息会多一行</p>
<pre class="line-numbers language-none"><code class="language-none">1) “pmessage”                     # 返回值的类型：信息
2) &quot;__keyspace@0__:cool*”         # 来源(从哪个ChannelPattern发送过来)
3) &quot;__keyspace@0__:cool&quot;          # 实际的Channel
4) “expired&quot;                      # 信息内容<span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span></span></code></pre>

<h2 id="Spring实现"><a href="#Spring实现" class="headerlink" title="Spring实现"></a>Spring实现</h2><p>最主要的是<code>KeyExpirationEventMessageListener</code>类,此类是对<code>MessageListener</code>接口的实现</p>
<p>看源码,它其实就是监听的一个<code>__keyevent@*__:expired</code>事件</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">KeyExpirationEventMessageListener</span> <span class="token keyword">extends</span> <span class="token class-name">KeyspaceEventMessageListener</span> <span class="token keyword">implements</span> <span class="token class-name">ApplicationEventPublisherAware</span> <span class="token punctuation">&#123;</span>
    <span class="token comment">//看这里-----------------------------------------------------------------------↓↓↓↓↓↓</span>
    <span class="token keyword">private</span> <span class="token keyword">static</span> <span class="token keyword">final</span> <span class="token class-name">Topic</span> KEYEVENT_EXPIRED_TOPIC <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">PatternTopic</span><span class="token punctuation">(</span><span class="token string">"__keyevent@*__:expired"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token annotation punctuation">@Nullable</span>
    <span class="token keyword">private</span> <span class="token class-name">ApplicationEventPublisher</span> publisher<span class="token punctuation">;</span>

    <span class="token keyword">public</span> <span class="token class-name">KeyExpirationEventMessageListener</span><span class="token punctuation">(</span><span class="token class-name">RedisMessageListenerContainer</span> listenerContainer<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">super</span><span class="token punctuation">(</span>listenerContainer<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">protected</span> <span class="token keyword">void</span> <span class="token function">doRegister</span><span class="token punctuation">(</span><span class="token class-name">RedisMessageListenerContainer</span> listenerContainer<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        listenerContainer<span class="token punctuation">.</span><span class="token function">addMessageListener</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">,</span> KEYEVENT_EXPIRED_TOPIC<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">protected</span> <span class="token keyword">void</span> <span class="token function">doHandleMessage</span><span class="token punctuation">(</span><span class="token class-name">Message</span> message<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">publishEvent</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">RedisKeyExpiredEvent</span><span class="token punctuation">(</span>message<span class="token punctuation">.</span><span class="token function">getBody</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>

    <span class="token keyword">protected</span> <span class="token keyword">void</span> <span class="token function">publishEvent</span><span class="token punctuation">(</span><span class="token class-name">RedisKeyExpiredEvent</span> event<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span>publisher <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
            <span class="token keyword">this</span><span class="token punctuation">.</span>publisher<span class="token punctuation">.</span><span class="token function">publishEvent</span><span class="token punctuation">(</span>event<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">&#125;</span>

    <span class="token punctuation">&#125;</span>

    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">setApplicationEventPublisher</span><span class="token punctuation">(</span><span class="token class-name">ApplicationEventPublisher</span> applicationEventPublisher<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">this</span><span class="token punctuation">.</span>publisher <span class="token operator">=</span> applicationEventPublisher<span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>我们只需要继承它,并重写<code>onMessage</code>即可</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Component</span>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">RedisKeyExpirationListener</span> <span class="token keyword">extends</span> <span class="token class-name">KeyExpirationEventMessageListener</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">public</span> <span class="token class-name">RedisKeyExpirationListener</span><span class="token punctuation">(</span><span class="token class-name">RedisMessageListenerContainer</span> container<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
        <span class="token keyword">super</span><span class="token punctuation">(</span>container<span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
  
    <span class="token comment">/**
     * 针对redis数据失效事件，进行数据处理
     * @param message
     * @param pattern
     */</span>
    <span class="token annotation punctuation">@Override</span>
    <span class="token keyword">public</span> <span class="token keyword">void</span> <span class="token function">onMessage</span><span class="token punctuation">(</span><span class="token class-name">Message</span> message<span class="token punctuation">,</span> <span class="token keyword">byte</span><span class="token punctuation">[</span><span class="token punctuation">]</span> pattern<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
       <span class="token class-name">String</span> key<span class="token operator">=</span>message<span class="token punctuation">.</span><span class="token function">toString</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment">//生效的key</span>
        <span class="token keyword">if</span> <span class="token punctuation">(</span>key<span class="token operator">!=</span><span class="token keyword">null</span> <span class="token operator">&amp;&amp;</span> key<span class="token punctuation">.</span><span class="token function">startsWith</span><span class="token punctuation">(</span><span class="token string">"order"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">&#123;</span><span class="token comment">//从失效key中筛选代表订单失效的key</span>
            <span class="token comment">//截取订单号，查询订单，如果是未支付状态则取消订单</span>
            <span class="token class-name">String</span> orderNo<span class="token operator">=</span>key<span class="token punctuation">.</span><span class="token function">substring</span><span class="token punctuation">(</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">"订单号为："</span><span class="token operator">+</span>orderNo<span class="token operator">+</span><span class="token string">"的订单超时未支付，取消订单"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  
        <span class="token punctuation">&#125;</span>
    <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>然后在<code>RedisConfig</code>中配置如下</p>
<pre class="line-numbers language-java" data-language="java"><code class="language-java"><span class="token annotation punctuation">@Bean</span>
<span class="token class-name">RedisMessageListenerContainer</span> <span class="token function">container</span><span class="token punctuation">(</span><span class="token class-name">RedisConnectionFactory</span> connectionFactory<span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token class-name">RedisMessageListenerContainer</span> container <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">RedisMessageListenerContainer</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    container<span class="token punctuation">.</span><span class="token function">setConnectionFactory</span><span class="token punctuation">(</span>connectionFactory<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token keyword">return</span> container<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span aria-hidden="true" class="line-numbers-rows"><span></span><span></span><span></span><span></span><span></span><span></span><span></span></span></code></pre>

<p>我们只需把过期事件设置为48小时,就实现了我们的需求</p>
<h2 id="缺陷"><a href="#缺陷" class="headerlink" title="缺陷"></a>缺陷</h2><ol>
<li><p>只能获取到失效的key，但是此时不能根据key获取value值，因为该事件是在数据失效后才触发</p>
<blockquote>
<p>有个简单的解决办法，就是一份数据存两份<br>比如你现在需要set一份数据：key：value<br>可以额外再set一份value相同但key有指定规则的数据：key_copy：value<br>第二份数据过期时间相对第一份数据稍微长一点<br>这样过期事件执行时可以拿着key根据指定的规则拼装出第二份数据的key，从而得到想要的value<br>缺点就是当你需要set的地方比较多时维护起来就非常恶心</p>
</blockquote>
</li>
<li><p>Redis的过期事件可能有点不准时,这是因为Redis本身的机制问题</p>
<blockquote>
<p>Redis有一下两种删除方式</p>
<ol>
<li>当键被访问时,程序会对键进行一次检查,如果以过期,那么键将被删除</li>
<li>底层系统会在后台随机查找并删除过期的键,从而处理这些已经过期,但未被查找的键</li>
</ol>
<p>当键被以上两个程序任意一个发现并删除时,Redis会产生一个expired通知</p>
<p>Redis并不保证生存时间变为0时会被立即删除,</p>
<p>如果程序没有访问这个键,或者带有过期事件的键非常多的话,那么在键的生存时间变为0时,直到真正删除这些键,会存在一个时间差,越多越明显.</p>
<p>因此,产生expired通知的时间才是过期键被删除的时间,而不是键的生存时间为0的时候.</p>
</blockquote>
</li>
</ol>
<h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2><p>文章1:<a target="_blank" rel="noopener" href="https://my.oschina.net/u/182501/blog/1927210">https://my.oschina.net/u/182501/blog/1927210</a></p>
<p>文章2:<a target="_blank" rel="noopener" href="https://blog.csdn.net/qijiqiguai/article/details/78229111">https://blog.csdn.net/qijiqiguai/article/details/78229111</a></p>
<p>文章3:<a target="_blank" rel="noopener" href="http://redisdoc.com/topic/notification.html">http://redisdoc.com/topic/notification.html</a></p>
<p>文章4:<a target="_blank" rel="noopener" href="https://segmentfault.com/a/1190000022735302">https://segmentfault.com/a/1190000022735302</a></p>
<p>文章5:<a target="_blank" rel="noopener" href="https://blog.csdn.net/for_the_time_begin/article/details/90376873">https://blog.csdn.net/for_the_time_begin/article/details/90376873</a></p>

  </div>
  <div>
    
      <div 
        class="post-note note-warning copyright" 
        style="margin-top: 42px">
        <p>
          <span style="font-weight: bold;">作者：</span><a 
            target="_blank" 
            rel="nofollow noopener noreferrer" 
            href="/about">
            Gas
          </a>
        </p>
        <p>
          <span style="font-weight: bold;">文章链接：</span><a 
            target="_blank" 
            rel="nofollow noopener noreferrer" 
            href="http://example.com/2021/08/06/SpringBoot-Redis-%E8%BF%87%E6%9C%9F%E4%BA%8B%E4%BB%B6/">
            http://example.com/2021/08/06/SpringBoot-Redis-%E8%BF%87%E6%9C%9F%E4%BA%8B%E4%BB%B6/
          </a>
        </p>
        <p><span style="font-weight: bold;">版权声明：</span>本博客所有文章除特别声明外，均采用<a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">CC BY-NC-SA 4.0 协议</a>。转载请注明出处！</p>
      </div>
    
  </div>
</article>
<div class="nav">
  
    <div class="nav-item-prev">
      <a 
        href="/2021/08/07/SpringBoot-Redis-%E6%B6%88%E6%81%AF%E9%98%9F%E5%88%97/" 
        class="nav-link">
        <i class="iconfont icon-left nav-prev-icon"></i>
        <div>
          <div class="nav-label">上一篇</div>
          
            <div class="nav-title">SpringBoot-Redis-消息队列 </div>
          
        </div>
      </a>
    </div>
  
  
    <div class="nav-item-next">
      <a 
        href="/2021/08/06/SpringBoot-Redis-%E5%8F%91%E5%B8%83%E8%AE%A2%E9%98%85/" 
        class="nav-link">
        <div>
          <div class="nav-label">下一篇</div>
          
            <div class="nav-title">SpringBoot-Redis-发布订阅 </div>
          
        </div>
        <i class="iconfont icon-right nav-next-icon"></i>
      </a>
    </div>
  
</div>

<div 
  class="card card-content toc-card" 
  id="mobiletoc">
  <div class="toc-header">
  <i 
    class="iconfont icon-menu" 
    style="padding-right: 2px;">
  </i>目录
</div>
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%9C%80%E6%B1%82"><span class="toc-number">1.</span> <span class="toc-text">需求</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AE%9E%E7%8E%B0"><span class="toc-number">2.</span> <span class="toc-text">实现</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8F%82%E6%95%B0%E8%A7%A3%E6%9E%90"><span class="toc-number">2.1.</span> <span class="toc-text">参数解析</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BA%8B%E4%BB%B6%E7%B1%BB%E5%9E%8B"><span class="toc-number">3.</span> <span class="toc-text">事件类型</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%AE%A2%E9%98%85"><span class="toc-number">4.</span> <span class="toc-text">订阅</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%91%BD%E4%BB%A4%E5%AE%9E%E8%B7%B5"><span class="toc-number">5.</span> <span class="toc-text">命令实践</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Spring%E5%AE%9E%E7%8E%B0"><span class="toc-number">6.</span> <span class="toc-text">Spring实现</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BC%BA%E9%99%B7"><span class="toc-number">7.</span> <span class="toc-text">缺陷</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8F%82%E8%80%83"><span class="toc-number">8.</span> <span class="toc-text">参考</span></a></li></ol>
</div></main>
            <aside class="left-column">
              
              <div class="card card-author">
                
  <img 
    src="/img/Kaze.png" 
    class="author-img" 
    alt="author avatar">

<p class="author-name">Gas</p>
<p class="author-description">想当画家的咸鱼罢了</p>
<div class="author-message">
  <a 
    class="author-posts-count" 
    href="/archives">
    <span>51</span>
    <span>文章</span>
  </a>
  <a 
    class="author-categories-count" 
    href="/categories">
    <span>16</span>
    <span>分类</span>
  </a>
  <a 
    class="author-tags-count" 
    href="/tags">
    <span>44</span>
    <span>标签</span>
  </a>
</div>

  <div class="author-card-society">
    
      <div class="author-card-society-icon">
        <a target="_blank" rel="noopener" href="https://github.com/Uranus-s">
          <i class="iconfont social_github icon-github society-icon"></i>
        </a>
      </div>
    
      <div class="author-card-society-icon">
        <a target="_blank" rel="noopener" href="https://gitee.com/L-sama">
          <i class="iconfont social_github icon-gitee2 society-icon"></i>
        </a>
      </div>
    
  </div>

              </div>
               <div class="sticky-tablet">
  
  
    <article class="display-when-two-columns spacer">
      <div class="card card-content toc-card">
        <div class="toc-header">
  <i 
    class="iconfont icon-menu" 
    style="padding-right: 2px;">
  </i>目录
</div>
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%9C%80%E6%B1%82"><span class="toc-number">1.</span> <span class="toc-text">需求</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AE%9E%E7%8E%B0"><span class="toc-number">2.</span> <span class="toc-text">实现</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8F%82%E6%95%B0%E8%A7%A3%E6%9E%90"><span class="toc-number">2.1.</span> <span class="toc-text">参数解析</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BA%8B%E4%BB%B6%E7%B1%BB%E5%9E%8B"><span class="toc-number">3.</span> <span class="toc-text">事件类型</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%AE%A2%E9%98%85"><span class="toc-number">4.</span> <span class="toc-text">订阅</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%91%BD%E4%BB%A4%E5%AE%9E%E8%B7%B5"><span class="toc-number">5.</span> <span class="toc-text">命令实践</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Spring%E5%AE%9E%E7%8E%B0"><span class="toc-number">6.</span> <span class="toc-text">Spring实现</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BC%BA%E9%99%B7"><span class="toc-number">7.</span> <span class="toc-text">缺陷</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8F%82%E8%80%83"><span class="toc-number">8.</span> <span class="toc-text">参考</span></a></li></ol>
      </div>
    </article>
  
  
  <article class="card card-content categories-widget">
    <div class="categories-card">
  <div class="categories-header">
    <i 
      class="iconfont icon-fenlei" 
      style="padding-right: 2px;">
    </i>分类
  </div>
  <div class="categories-list">
    
      <a href="/categories/Java/">
        <div class="categories-list-item">
          Java
          <span class="categories-list-item-badge">11</span>
        </div>
      </a>
    
      <a href="/categories/SpringBoot/">
        <div class="categories-list-item">
          SpringBoot
          <span class="categories-list-item-badge">16</span>
        </div>
      </a>
    
      <a href="/categories/WPF/">
        <div class="categories-list-item">
          WPF
          <span class="categories-list-item-badge">1</span>
        </div>
      </a>
    
      <a href="/categories/Docker/">
        <div class="categories-list-item">
          Docker
          <span class="categories-list-item-badge">3</span>
        </div>
      </a>
    
      <a href="/categories/Net/">
        <div class="categories-list-item">
          Net
          <span class="categories-list-item-badge">2</span>
        </div>
      </a>
    
      <a href="/categories/DotNetCore/">
        <div class="categories-list-item">
          DotNetCore
          <span class="categories-list-item-badge">2</span>
        </div>
      </a>
    
      <a href="/categories/%E6%8E%92%E5%BA%8F/">
        <div class="categories-list-item">
          排序
          <span class="categories-list-item-badge">1</span>
        </div>
      </a>
    
      <a href="/categories/Redis/">
        <div class="categories-list-item">
          Redis
          <span class="categories-list-item-badge">6</span>
        </div>
      </a>
    
      <a href="/categories/COS/">
        <div class="categories-list-item">
          COS
          <span class="categories-list-item-badge">1</span>
        </div>
      </a>
    
      <a href="/categories/Spring/">
        <div class="categories-list-item">
          Spring
          <span class="categories-list-item-badge">1</span>
        </div>
      </a>
    
      <a href="/categories/IText/">
        <div class="categories-list-item">
          IText
          <span class="categories-list-item-badge">1</span>
        </div>
      </a>
    
      <a href="/categories/GateWay/">
        <div class="categories-list-item">
          GateWay
          <span class="categories-list-item-badge">1</span>
        </div>
      </a>
    
      <a href="/categories/Jenkins/">
        <div class="categories-list-item">
          Jenkins
          <span class="categories-list-item-badge">1</span>
        </div>
      </a>
    
      <a href="/categories/Netty/">
        <div class="categories-list-item">
          Netty
          <span class="categories-list-item-badge">1</span>
        </div>
      </a>
    
      <a href="/categories/Log4j/">
        <div class="categories-list-item">
          Log4j
          <span class="categories-list-item-badge">1</span>
        </div>
      </a>
    
      <a href="/categories/algorithm/">
        <div class="categories-list-item">
          algorithm
          <span class="categories-list-item-badge">1</span>
        </div>
      </a>
    
  </div>
</div>
  </article>
  
  <article class="card card-content tags-widget">
    <div class="tags-card">
  <div class="tags-header">
    <i 
      class="iconfont icon-biaoqian" 
      style="padding-right: 2px;">
    </i>热门标签
  </div>
  <div class="tags-list">
    
      <a 
        href="/tags/SpringBoot/" 
        title="SpringBoot">
        <div class="tags-list-item">SpringBoot</div>
      </a>
    
      <a 
        href="/tags/Spring/" 
        title="Spring">
        <div class="tags-list-item">Spring</div>
      </a>
    
      <a 
        href="/tags/Java/" 
        title="Java">
        <div class="tags-list-item">Java</div>
      </a>
    
      <a 
        href="/tags/Redis/" 
        title="Redis">
        <div class="tags-list-item">Redis</div>
      </a>
    
      <a 
        href="/tags/Docker/" 
        title="Docker">
        <div class="tags-list-item">Docker</div>
      </a>
    
      <a 
        href="/tags/DotNetCore/" 
        title="DotNetCore">
        <div class="tags-list-item">DotNetCore</div>
      </a>
    
      <a 
        href="/tags/IDEA/" 
        title="IDEA">
        <div class="tags-list-item">IDEA</div>
      </a>
    
      <a 
        href="/tags/Maven/" 
        title="Maven">
        <div class="tags-list-item">Maven</div>
      </a>
    
      <a 
        href="/tags/RabbitMQ/" 
        title="RabbitMQ">
        <div class="tags-list-item">RabbitMQ</div>
      </a>
    
      <a 
        href="/tags/Jackson/" 
        title="Jackson">
        <div class="tags-list-item">Jackson</div>
      </a>
    
      <a 
        href="/tags/snowflake/" 
        title="snowflake">
        <div class="tags-list-item">snowflake</div>
      </a>
    
      <a 
        href="/tags/algorithm/" 
        title="algorithm">
        <div class="tags-list-item">algorithm</div>
      </a>
    
      <a 
        href="/tags/Log4j/" 
        title="Log4j">
        <div class="tags-list-item">Log4j</div>
      </a>
    
      <a 
        href="/tags/Socket/" 
        title="Socket">
        <div class="tags-list-item">Socket</div>
      </a>
    
      <a 
        href="/tags/Netty/" 
        title="Netty">
        <div class="tags-list-item">Netty</div>
      </a>
    
      <a 
        href="/tags/Jenkins/" 
        title="Jenkins">
        <div class="tags-list-item">Jenkins</div>
      </a>
    
  </div>
</div>
  </article>
  
  
</div>
            </aside>
            <aside class="right-column">
              <div class="sticky-widescreen">
  
  
    <article class="card card-content toc-card">
      <div class="toc-header">
  <i 
    class="iconfont icon-menu" 
    style="padding-right: 2px;">
  </i>目录
</div>
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%9C%80%E6%B1%82"><span class="toc-number">1.</span> <span class="toc-text">需求</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%AE%9E%E7%8E%B0"><span class="toc-number">2.</span> <span class="toc-text">实现</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8F%82%E6%95%B0%E8%A7%A3%E6%9E%90"><span class="toc-number">2.1.</span> <span class="toc-text">参数解析</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BA%8B%E4%BB%B6%E7%B1%BB%E5%9E%8B"><span class="toc-number">3.</span> <span class="toc-text">事件类型</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%AE%A2%E9%98%85"><span class="toc-number">4.</span> <span class="toc-text">订阅</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%91%BD%E4%BB%A4%E5%AE%9E%E8%B7%B5"><span class="toc-number">5.</span> <span class="toc-text">命令实践</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Spring%E5%AE%9E%E7%8E%B0"><span class="toc-number">6.</span> <span class="toc-text">Spring实现</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BC%BA%E9%99%B7"><span class="toc-number">7.</span> <span class="toc-text">缺陷</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8F%82%E8%80%83"><span class="toc-number">8.</span> <span class="toc-text">参考</span></a></li></ol>
    </article>
  
  
  <article class="card card-content">
    <div class="recent-posts-card">
  <div class="recent-posts-header">
    <i 
      class="iconfont icon-wenzhang_huaban" 
      style="padding-right: 2px;">
    </i>最近文章
  </div>
  <div class="recent-posts-list">
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2022-07-08</div>
        <a href="/2022/07/08/SpringBoot-RabbitMQ%E5%BA%94%E7%94%A8/"><div class="recent-posts-item-content">SpringBoot-RabbitMQ应用</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2022-03-26</div>
        <a href="/2022/03/26/IDEA%E9%83%A8%E7%BD%B2Docker%E9%A0%85%E7%9B%AE/"><div class="recent-posts-item-content">IDEA部署Docker項目</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2022-03-04</div>
        <a href="/2022/03/04/%E5%9F%BA%E4%BA%8EJackson%E7%9A%84JsonFilter%E5%AE%9E%E7%8E%B0%E5%8A%A8%E6%80%81%E6%95%B0%E6%8D%AE%E5%A1%AB%E5%86%99/"><div class="recent-posts-item-content">基于Jackson的JsonFilter实现动态数据填写</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2022-02-16</div>
        <a href="/2022/02/16/SpringBoot-%E8%87%AA%E5%AE%9A%E4%B9%89%E6%B3%A8%E8%A7%A3%E5%8D%95%E5%8F%82%E6%95%B0Post/"><div class="recent-posts-item-content">SpringBoot-自定义注解单参数Post</div></a>
      </div>
    
  </div>
</div>
  </article>
  
  
</div>
            </aside>
          </div>
        </div>
      </div>
    </div>
     
    <footer class="footer">
  <div class="footer-container">
    <div>
      <div class="footer-dsc">
        <span>
          Copyright ©
          
            2020 -
          
          2022
        </span>
        &nbsp;
        <a 
          href="/" 
          class="footer-link">
          Gas
        </a>
      </div>
    </div>

    
      <div class="footer-dsc">
        
          Powered by
          <a 
            href="https://hexo.io/" 
            class="footer-link" 
            target="_blank" 
            rel="nofollow noopener noreferrer">
            &nbsp;Hexo
          </a>
        
        
          <span>&nbsp;|&nbsp;</span>
        
        
          Theme -
          <a 
            href="https://github.com/theme-kaze" 
            class="footer-link" 
            target="_blank"
            rel="nofollow noopener noreferrer">
            &nbsp;Kaze
          </a>
        
      </div>
    
    
    
    
      <div class="footer-dsc">
        
          本站总访问量<span id="busuanzi_value_site_pv"></span>次
        
        
          <span>&nbsp;|&nbsp;</span>
        
        
          本站总访客数<span id="busuanzi_value_site_uv"></span>次
        
      </div>
      
    
</footer> 
    
  <a 
    role="button" 
    id="scrollbutton" 
    class="basebutton" 
    aria-label="回到顶部">
    <i class="iconfont icon-arrowleft button-icon"></i>
  </a>

<a 
  role="button" 
  id="menubutton" 
  class="basebutton">
  <i class="iconfont icon-menu button-icon"></i>
</a>
<a 
  role="button" 
  id="popbutton" 
  class="basebutton" 
  aria-label="控制中心">
  <i class="iconfont icon-expand button-icon"></i>
</a>
<a 
  role="button" 
  id="darkbutton" 
  class="basebutton darkwidget" 
  aria-label="夜色模式">
  <i class="iconfont icon-weather button-icon"></i>
</a>
<a 
  role="button" 
  id="searchbutton" 
  class="basebutton searchwidget" 
  aria-label="搜索">
  <i class="iconfont icon-search button-icon"></i>
</a> 
     
     
     
      <script>
  var addImgLayout = function () {
    var img = document.querySelectorAll('.post-content img')
    var i
    for (i = 0; i < img.length; i++) {
      var wrapper = document.createElement('a')
      wrapper.setAttribute('href', img[i].getAttribute('data-src'))
      wrapper.setAttribute('aria-label', 'illustration')
      wrapper.style.cssText =
        'width: 100%; display: flex; justify-content: center;'
      if (img[i].alt) wrapper.dataset.caption = img[i].alt
      wrapper.dataset.nolink = true
      img[i].before(wrapper)
      wrapper.append(img[i])
      var divWrap = document.createElement('div')
      divWrap.classList.add('gallery')
      wrapper.before(divWrap)
      divWrap.append(wrapper)
    }
    baguetteBox.run('.gallery')
  }
</script>
<script>
  loadScript(
    "/js/lib/lightbox/baguetteBox.min.js",
    addImgLayout
  )
</script>
 
     
     
    <script src="/js/main.js"></script> 
    
      <script> 
        loadScript('/js/lib/busuanzi.min.js') 
      </script>
     
    
      <script>
        var addLazyload = function () {
          var observer = lozad('.lozad', {
            load: function (el) {
              el.srcset = el.getAttribute('data-src')
            },
            loaded: function (el) {
              el.classList.add('loaded')
            },
          })
          observer.observe()
        }
      </script>
      <script>
        loadScript('/js/lib/lozad.min.js', addLazyload)
      </script>
     
    
    
      <script>
        setTimeout(() => {localSearch("search.json")}, 0)
      </script>
    
  </body>
</html>
